package org.cn.springcloudvv.cxf.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.cn.springcloudvv.cxf.annation.AutoPublishWS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@Order(1)
public class WebservicePublishApplicationRunner implements ApplicationRunner {

    @Value("${cxf.path}")
    public String cxfPath;

    @Value("${spring.application.name}")
    public String appName;

    @Autowired
    private Bus bus;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("publish begin ======");
        String[] beanNames = webApplicationContext.getBeanNamesForAnnotation(AutoPublishWS.class);
        EndpointImpl endpoint;
        List<String> cxfPathList = new ArrayList<>();
        for (String beanName : beanNames) {
            String publishPath = webApplicationContext.getType(beanName).getAnnotation(AutoPublishWS.class).publishPath();
            //发布WebService接口
            endpoint = new EndpointImpl(bus, webApplicationContext.getBean(beanName));
            //endpoint.getInInterceptors().add(new WsOutInterceptor());
            endpoint.publish(publishPath);
            cxfPathList.add(publishPath);
            log.info(String.format("%s", publishPath));
        }
        log.info("publish success ======");

    }

}
